package ua.com.softway.db;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.apache.log4j.xml.DOMConfigurator;

public class DatabaseTool {
    private static EntityTransaction transaction;
    private static EntityManager entityManager;

    public static void begin() {
        DOMConfigurator.configure("log4j.xml");
        
        Persistence.init();
        Persistence.setCurrentEntityManager(Persistence.getEntityManagerFactory().createEntityManager());
        
        EntityManagerFactory entityManagerFactory = Persistence.getEntityManagerFactory();
        
        entityManager = entityManagerFactory.createEntityManager();
        Persistence.setCurrentEntityManager(entityManager);
        
        transaction = entityManager.getTransaction();
        transaction.begin();
    }
    
    public static void end() {
        transaction.commit();

        entityManager.close();
        Persistence.setCurrentEntityManager(null);
    }
    
    public static void rollback() {
        transaction.commit();
        
        entityManager.close();
        Persistence.setCurrentEntityManager(null);
    }
}
